package com.net.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.net.mapper.TbBrandMapper;
import com.net.pojo.PageResult;
import com.net.pojo.TbBrand;
import com.net.service.BrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class BrandServiceImpl implements BrandService {

    @Autowired
    private TbBrandMapper brandMapper;

    //1.查询所有品牌
    @Override
    public List<TbBrand> findAll() {
        return brandMapper.selectAll();
    }

    //条件查询带分页
    @Override
    public PageResult search(TbBrand brand, int page, int pageSize) {
        //开始分页
        PageHelper.startPage(page, pageSize);
        //开始进行条件查询
        Example example = new Example(TbBrand.class);
        Example.Criteria criteria = example.createCriteria();
        //添加查询条件
        if (brand != null) {
           if (StringUtils.isNotBlank(brand.getName())) {
                criteria.andLike("name", "%" + brand.getName() + "%");
            }
           if (StringUtils.isNotBlank(brand.getFirstChar())) {
                criteria.andEqualTo("firstChar", brand.getFirstChar());
            }
        }
        //进行条件查询
        List<TbBrand> tbBrands = brandMapper.selectByExample(example);
        //转换为Page<TbBrand>对象
        Page<TbBrand> brandPage = (Page<TbBrand>) tbBrands;
        //返回
        return new PageResult(brandPage.getTotal(), brandPage.getResult());
    }

    //添加品牌
    @Override
    public void add(TbBrand brand) {
        brandMapper.insert(brand);
    }

    //修改品牌
    @Override
    public void update(TbBrand brand) {
        brandMapper.updateByPrimaryKey(brand);
    }

    //删除品牌
    @Override
    public void delete(Long[] ids) {
        //遍历数组id
        for (Long id : ids) {
            //删除每一个id对应的品牌
            brandMapper.deleteByPrimaryKey(id);
        }
    }
}
